package com.dtkavin.threads;

/**
 * Created by john on 10/3/16.
 * 互斥
 * 设计观念：高内聚，同步的相关方法封装到一起，对外不显示同步特性，这样做好维护，不用在线程中维护，直接在这个类中维护即可
 */
public class SynchronizedTrueDemo {

    private final int count = 100;//打印循环总次数

    public void threadRun1() {
        new Thread(new Runnable() {
            public void run() {

            }
        }).start();
    }

    public void threadRun2() {
        new Thread(new Runnable() {
            public void run() {

            }
        }).start();
    }

    /**
     * 如果要做到互斥，轮流的打印，需要通过wait和notify来唤醒
     */
    class RunShare {
        private boolean lock = true;//true时打印2，false时打印1

        /**
         * print1 打印10次
         */
        public synchronized void print1() {
            while (lock) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("print1--1--1--1--1");
            }
            lock = true;
            this.notify();
        }

        /**
         * print2 打印15次
         */
        public synchronized void print2() {
            while (!lock) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 15; i++) {
                System.out.println("print2--2--2--2--2");
            }
            lock = false;
            this.notify();
        }
    }
}
